﻿using System;
using System.Collections.Generic;
using System.Text;
using TCPSockets;
using System.IO;

namespace Galaxy.Portal.TCP
{
    /// <summary>Входящее соединение</summary>
    class CIncomingConnection
    {
        /// <summary>Аргумент события завершения соединения</summary>
        public class OnConnectionCompliteEventArgs : EventArgs
        {
            /// <summary>Поток данных соединения</summary>
            public Stream DataStream;
            
            public OnConnectionCompliteEventArgs(Stream DataStream)
            {
                this.DataStream = DataStream;
            }
        }

        /// <summary>Обработчик события завершения соединения</summary>
        /// <param name="Connection">Соединение</param>
        /// <param name="Arg">Аргумент завершения соединения</param>
        public delegate void OnConnectionCompliteEventHandler(CIncomingConnection Connection,
            OnConnectionCompliteEventArgs Arg);

        /// <summary>Событие завершения соединения</summary>
        public event OnConnectionCompliteEventHandler OnConnectionComplite;

        protected virtual void Invoke_OnConnectionComplite(Stream DataStream)
        {
            DataStream.Position = 0;
            if(OnConnectionComplite != null)
                OnConnectionComplite.Invoke(this, new OnConnectionCompliteEventArgs(DataStream));
        }

        private void Invoke_OnConnectionComplite()
        {
            Invoke_OnConnectionComplite(f_DataStream);
        }

        private Stream f_DataStream = new TempFileStream();

        public CIncomingConnection(CTCPClient Client, CTCPPortal Portal)
        {
            Client.OnDisconnected += delegate { Invoke_OnConnectionComplite(); };
            Client.OnReceiveData += OnClientReceiveData;
        }

        private void OnClientReceiveData(CTCPClient Client, TCPSockets.ClientEvents.Args.DataEventArgs Args)
        {
            f_DataStream.Write(Args.Data, 0, Args.Data.Length);
        }
    }
}
